<?php
/*
 * @See Clu_Db_Table_Abstract
 */
class comment_Model_Service extends Clu_Db_Table_Abstract
{
    //only specify the table name, everything else inherits
	protected $_name = "comments";
	protected $_primary = "id";

	public function findByPrimary($id)
	{
		if (!$id)
            return null;
        else
		    return $this->fetchRow('id = ' . $this->getAdapter()->quote($id, 'INTEGER'));
		        
	}
	
	public function insertRaw($data ,$doValidate = false)
	{ 
		$sess = new Zend_Session_Namespace(CLU_NS);
		if ($doValidate)
    	{
    		$form = new comment_Form_Comment();
    		if (!$form->isValid($data))
    			return false;
		}
		
		$a = array();
	    if (isset($data['language']))
		    $a['language'] 		= $data['language'];
		else 
			$a['language'] 		=  $sess->viewLang;
			
	    $a['comment_text'] 			= $data['comment_text'];
	    
	    if($data['content_type'] != 'user')
	    {
			$a['status']				= 'queued';
			$a['title'] 				= $data['title'];
			if(isset($data['pid'])!=0 && isset($data['pid']))
			{
				$var = $this->findByPrimary($data['pid']);
				if($var['pid'] == 0)
					$a['pid']					= $data['pid'];
	    	    else
	    	    {
	    		    $a['pid']					= $var['pid'];
	    	    	$a['reply_to']				= $data['pid'];
	    	    }
		    	$db = $this->getAdapter() ;
		    	$sql = "UPDATE comments set number_of_children = number_of_children +1 WHERE id=".$a['pid'];
		    	$db->query($sql);
			}
	    }
		
		if ($sess->userId)
		{
			$a['poster_id'] 		= $sess->userId;
			$a['poster_name'] 		= $sess->userName;
		}
		else
		{
			$a['poster_id'] 		= 0;
			$a['poster_name'] 		= $data['poster_name'];
			$a['guest_email'] 		= $data['guest_email'];
		}
			 
		$a['content_id']		= $data['content_id'];
		$a['content_type']	= $data['content_type'];
		$a['created'] = time();
		
	    return $this->insert($a);
	}
	
	public function saveRaw($c, $data, $id, $doValidate)
	{
	    if ((!$c) && (!$id))
	    	return false;
	    else if (!$c)
	       	if (!$c = $this->findByPrimary($id))
	       		return false;
	    $c['comment_text'] 	= $data['comment_text'] ;
	    $c['title'] 		= $data['title'] ;
	    $c['poster_name']	= $data['poster_name'] ;
	    $c['guest_email'] 	= $data['guest_email'] ;
	    $c['status'] 		= $data['status'] ;
	    $c['language'] 		= $data['language'] ;
	    
	    if ($doValidate)
	    {
	    	//Validate Data here
	    }
//	    $a->setFromArray($data);
        return $c->save();
	}

	public function deleteByPrimary($idArray, $atomic = true)
	{
        $db = $this->getAdapter();
        if ($atomic)
	        $db->beginTransaction(); //@NOTE: no effect with MyISAM
		try
        {
        	foreach($idArray as $array=>$ids)
			{
    	    	$Var = $this->findByPrimary($ids);
    	    	$abc = $Var['pid'];
                $sql0 = "DELETE FROM comments WHERE pid =". (int)$db->quote($ids, 'INTEGER');
                $db->query($sql0);
               	$sql1 = "UPDATE comments SET number_of_children = (number_of_children -1)  WHERE id =". (int)$db->quote($abc, 'INTEGER');
            	$db->query($sql1);
               	$sql2 = "DELETE FROM comments WHERE id =". (int)$db->quote($ids, 'INTEGER');
               	$db->query($sql2);
			}
           	if ($atomic)
	            $db->commit();
            return true;
    	}
        catch (Exception $e)
        {
            if ($atomic)
	            $db->rollBack();
            return false;
        }
	}

	public function searchChildrenList($data)
	{
		$pid = isset($data['id']) ? $data['id']:null;
		
		$db = $this->getAdapter();
    	$select = new Zend_Db_Select($db);
		$select    = $db->select()
						->distinct();

        // Add a FROM clause
        $select->from( array('c' => 'comments'))
        	   ->where('c.pid = ?',(int)$db->quote($pid,"INT"));
        return $select;	
	}
	public function search($data)
	{
		if(!is_array($data))
		{
			$db = $this->getAdapter();
			$select = $db->select();
	        $select->from( array('c' => 'comments') );
			if($data)
    			$select->where('c.content_id = ?', (int)$db->quote($data,"INT"));
		}
		else
		{
			$language 			= isset($data['language'])? $data['language']:null;
	   		$rating 			= isset($data['rating'])?$data['rating']:null;
			$parentId 			= isset($data['content_id']) ? $data['content_id'] : null;
			$parentType 		= isset($data['content_type'])? $data['content_type'] : null; 
			$status 			= isset($data['status']) ? $data['status']:null;
	    	$ratingOperator		= isset($data['ratingOperator']) ? $data['ratingOperator']:null;
	    	
			//value admin search
	    	$to_rating 			= isset($data['to_rating'])?$data['to_rating']:null;
	    	$ascOrDesc 			= isset($data['asc_or_desc']) ? $data['asc_or_desc']:null;
	    	$orderBy 			= isset($data['orderBy'])?$data['orderBy']:null;
	   	
	    	$poster_id 		= isset($data['poster_id']) ? $data['poster_id']:null;
	    	$reply_to 			= isset($data['reply_to']) ? $data['reply_to']:null;
	    	$pid 				= isset($data['pid']) ? $data['pid']:null;
	    	$searchTime 		= isset($data['searchTime']) ? $data['searchTime']:null;
	    	$checkTime			= isset($data['checkTime']) ? $data['checkTime']:null;
		
	    	//select SQL query
	    	$db = $this->getAdapter();
			$select = $db->select();
	//				     ->distinct();
			
			// Add a FROM clause
	        $select->from( array('c' => 'comments') );
	        
			switch($parentType)
	        {
	            case 'all':
	            {
	            /*	$place = new place_Model_Place();
	            	$artice = new article_Model_Service();
	            	$select->join(array('p' => 'places','a' => 'article'),'', array('p.name','a.article_title'));
	            	$select->where('c.content_id = p.id');
	            	$select->orwhere('c.content_id = a.article_id');*/
	            	break;
	            }
	            case 'place':
	            {
	                $place = new place_Model_Place();
	                $select->join(array('p' => 'places'),'', array('p.name'));
	                $select->where('c.content_id = p.id');
	            	break;
	            }
	            case 'news' :
	            {
	            
	            	break;
	            }
	            case 'user' :
	            {
	            	$user = new user_Model_User();
	                $select->join(array('u' => 'users'),'', array('u.name'));
	                $select->where('c.content_id = ?',$parentId);
	            	break;
	            }
	            case 'event':
	            {
	            	$event = new event_Model_Service();
	                $select->join(array('e' => 'events'),'', array('e.title'));
	                $select->where('c.content_id = e.id');
	            	break;
	            }
	            
	            case 'blog' :
	        	{
	                //$select->join(array('b' => 'blog'),'', array('b.title'));
	                //$select->where('c.content_id = ?', $parentId);
	            	break;
	            }
	        }
	        
	        // Add a WHERE clause 
	        if($parentType && $parentType != 'all') //
	    		$select->where('c.content_type = ?', $db->quoteinto($parentType,'STRING'));
	    	
	    	if($language && $language != 'all')
	    		$select->where('c.language = ?', $db->quoteinto($language,'STRING'));
	    	
	    	if($status && $status != 'all' )
	    		$select->where('c.status = ?', $db->quoteinto($status,'STRING'));
	    	
	    	// not show in search.phtml
	    	if($parentId)
	    		$select->where('c.content_id = ?', (int)$db->quote($parentId,"INT"));
	
	    	if($poster_id)
	    		$select->where('c.poster_id = ?', (int)$db->quote($poster_id,"INT"));
	    		
	    	if($pid)
	    		$select->where('c.pid = ?', (int)$db->quote($pid,"INT"));
	    		
	    	if($reply_to)
	    		$select->where('c.reply_to = ?', (int)$db->quote($reply_to,"INT"));
	
	    	switch($ratingOperator)
	    	{
	    		case 'before'  :{
	    			$select->where('c.rating <= ?',(int)$db->quote($rating,"INT"));
					break;    			
	    		}
	    		case 'after'   :{
	    			$select->where('c.rating >= ?',(int)$db->quote($rating,"INT"));
					break;    			
	    		}
	    		case 'none'	   :{
	    			if($rating)
	    				$select->where('c.rating = ?',(int)$db->quote($rating,"INT"));
	    			break;
	    		}
	    		case 'between' :{
	        		$select->where('c.rating >= ?',(int)$db->quote($rating,"INT"));
	        		$select->where('c.rating <= ?',(int)$db->quote($to_rating,"INT"));
	        		break;
	    		}
	    		default : break;
	    	}
	    	 
			if($searchTime == 'detail')
	    	{
				$tmp  = 60*60*24 ;
				$time = getdate();
				switch($checkTime)
				{
	    			case 1:
	    			{
	    				$select->where('c.created >= ?',($time['0'] - $tmp));
	    				break;
	    			}
	    			case 2:
					{
	    				$select->where('c.created >= ?',($time['0'] - $tmp*7));
	    				break;
	    			}
	    			case 3:
					{
	    				$select->where('c.created >= ?',($time['0'] - $tmp*300));
	    				break;
	    			}
				}    	
	    	}
	    	else
	    	{
	    		
	    	}
	        // Add an ORDER BY clause
	        switch($orderBy)
	        {
	        	case 'time':{
	                $select->order(array(sprintf('c.created %s',$db->quoteinto($ascOrDesc,'STRING')))); //to_String();
	               	break;
	        	}
	        	case 'rating':{
	                $select->order(array(sprintf('c.rating %s',$db->quoteinto($ascOrDesc,'STRING'))));
	               	break;
	        	}
	        	case 'rating_count':{
	                $select->order(array(sprintf('c.rating_count %s',$db->quoteinto($ascOrDesc,'STRING'))));
	               	break;
	        	}
	        }
	        $select->group('c.id');
		}
//     	die($select);
		return $select;
	}
	
	public function bulkUpdateStatus($idArray, $data)
	{
		$idList = implode (',', $idArray);
		$db = $this->getAdapter() ;
        $db->beginTransaction();
        try {
        	if($data['status'] == 'deleted')
        	{
            	$sql0 = "UPDATE comments SET status = ".$db->quote($data['status'],'STRING')." WHERE pid IN (".$idList.")" ;
	            $db->query($sql0);
        	}
            $sql =  "UPDATE comments SET status = ".$db->quote($data['status'],'STRING')." WHERE id IN (".$idList.")" ;
            $db->query($sql);
            $db->commit();
			return true;
        }    
        catch (Exception $e)
        {
            $db->rollBack();
            return false;
        }   	
	}
}
?>